const gulp = require('gulp')
const pug = require('gulp-pug')
const concat = require('gulp-concat')
const uglify = require('gulp-uglify')
const imagemin = require('gulp-imagemin')
const sourcemaps = require('gulp-sourcemaps')
const del = require('del')
const less = require('gulp-less')
const cleancss = require('gulp-clean-css')
const csscomb = require('gulp-csscomb')
const rename = require('gulp-rename')
const LessPluginAutoPrefix = require('less-plugin-autoprefix')
const autoprefix = new LessPluginAutoPrefix({ browsers: ["last 4 versions"] })
const browserSync = require('browser-sync').create()

const paths = {
  scripts: 'src/scripts/*.js',
  images: 'src/assets/images/*',
  pages: 'src/pages/*.pug',
  styles: 'src/styles/*.less'
}

gulp.task('clean', function() {
  return del(['dist', 'test'])
})

gulp.task('pug', function() {
  return gulp.src(paths.pages)
    .pipe(pug())
    .pipe(gulp.dest('test'))
})

gulp.task('less', function() {
  return gulp.src(paths.styles)
    .pipe(less({
      plugins: [autoprefix]
    }))
    .pipe(csscomb())
    .pipe(gulp.dest('dist/css'))
    .pipe(cleancss())
    .pipe(rename({
      suffix: '.min'
    }))
    .pipe(gulp.dest('dist/css'))
})

gulp.task('js', function() {
  return gulp.src(paths.scripts)
    .pipe(gulp.dest('dist/js'))
    .pipe(sourcemaps.init())
    .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(rename({
      suffix: '.min'
    }))
    .pipe(gulp.dest('dist/js'))
    .pipe(concat('siwi.min.js'))
    .pipe(gulp.dest('dist/js'))

})

gulp.task('images', function() {
  return gulp.src(paths.images)
    .pipe(imagemin({ optimizationLevel: 5 }))
    .pipe(gulp.dest('dist/images'))
})

gulp.task('watch', function() {
  gulp.watch('src/styles/*.less', ['less'])
  gulp.watch('src/scripts/*.js', ['js'])
  gulp.watch('src/pages/*.pug', ['pug'])
});

gulp.task('serve', ['pug', 'less', 'js'], function() {

  browserSync.init({
    server: "./test"
  })
  gulp.watch("src/pages/*.pug", ['pug'])
  gulp.watch("src/styles/*.less", ['less'])
  gulp.watch("src/scripts/*.js", ['js'])
  gulp.watch("test/*.html").on('change', browserSync.reload)
})

gulp.task('default', ['pug', 'les', 'js'])